package com.bxait.toymail.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.bxait.com.exception.order.NoStockException;
import com.bxait.com.to.mq.OrderTo;
import com.bxait.com.to.mq.SecKillOrderTo;
import com.bxait.com.utils.PageUtils;
import com.bxait.com.utils.Query;
import com.bxait.com.utils.R;
import com.bxait.com.vo.member.MemberRespVo;
import com.bxait.toymail.order.constant.OrderConstant;
import com.bxait.toymail.order.entity.OrderItemEntity;
import com.bxait.toymail.order.enume.OrderStatusEnum;
import com.bxait.toymail.order.feign.CartFeignService;
import com.bxait.toymail.order.feign.MemberFeignService;
import com.bxait.toymail.order.feign.ProductFeignService;
import com.bxait.toymail.order.feign.WmsFeignService;
import com.bxait.toymail.order.interceptor.LoginUserInterceptor;
import com.bxait.toymail.order.service.OrderItemService;
import com.bxait.toymail.order.service.PaymentInfoService;
import com.bxait.toymail.order.to.OrderCreateTo;
import com.bxait.toymail.order.vo.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.bxait.toymail.order.dao.OrderDao;
import com.bxait.toymail.order.entity.OrderEntity;
import com.bxait.toymail.order.service.OrderService;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal = new ThreadLocal<>();

    @Resource
    RabbitTemplate rabbitTemplate;
    @Resource
    @Qualifier("paymentInfoService")
    PaymentInfoService paymentInfoService;
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Resource
    @Qualifier("orderItemService")
    OrderItemService orderItemService;
    @Resource
    MemberFeignService memberFeignService;
    @Resource
    ProductFeignService productFeignService;
    @Resource
    CartFeignService cartFeignService;
    @Resource
    WmsFeignService wmsFeignService;
    @Resource
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    /*
     * @param
     * @==============History===============<br/>
     * @Description //   处理购物车结算请求
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return OrderConfirmVo
     */
    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {
        // 订单确认页需要使用的数据
        OrderConfirmVo confirmVo = new OrderConfirmVo();
        // 获取用户对象
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        //获取之前的请求
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 1、远程查询所有的收货地址列表
        final CompletableFuture<Void> getAddressFuture = CompletableFuture.runAsync(() -> {
            // 每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
            confirmVo.setAddress(address);
        }, executor);

        // 2、远程查询购物车所有选中的购物项
        final CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            // 每一个线程都来共享之前的请求数据
            RequestContextHolder.setRequestAttributes(requestAttributes);
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            // 查询订单中的商品库存信息
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());
            // 查询库存信息
            R hasStock = wmsFeignService.getSkusHasStock(collect);
            List<SkuStockVo> data = hasStock.getData(new TypeReference<List<SkuStockVo>>() {});
            if (data != null) {
                Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
                confirmVo.setStocks(map);
            }
        });

        // 3、查询用户积分
        // 在当前登录的用户中就可以获取到
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

        // 4、其他数据自动计算

        // 5、防重令牌
        String token = UUID.randomUUID().toString().replace("-", "");
        // 将令牌保存到redis中
        stringRedisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId(), token, 30, TimeUnit.MINUTES);
        confirmVo.setOrderToken(token);

        // 6.等待所以请求处理完成
        CompletableFuture.allOf(getAddressFuture, cartFuture).get();

        confirmVo.setTotal(getTotal(confirmVo.getItems()));

        return confirmVo;
    }

    public BigDecimal getTotal(List<OrderItemVo> items) {
        BigDecimal sum = new BigDecimal("0");
        if(items!=null){
            for (OrderItemVo item : items) {
                BigDecimal multiply = item.getPrice().multiply(new BigDecimal(item.getCount().toString()));
                sum = sum.add(multiply);
            }
        }

        return sum;
    }



    /*
     * @param vo
     * @==============History===============<br/>
     * @Description //   下单操作
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return com.bxait.toymail.order.vo.SubmitOrderResponseVo
     */
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo submitVo) {
        // 将页面上收集上来的需要创建的订单信息保存在本地线程中
        confirmVoThreadLocal.set(submitVo);
        // 准备响应数据
        SubmitOrderResponseVo response = new SubmitOrderResponseVo();
        // 获取登录的用户登录的信息
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        // 设置默认下单为成功
        response.setCode(0);

        // 1、验证令牌【令牌的对比和删除必须保证原子性】 0令牌失败 - 1删除成功
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        final String orderToken = submitVo.getOrderToken();
        // 原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);
        // 令牌验证失败
        if(result == 0L){
            response.setCode(1);
            return response;
        }
        // 令牌验证成功
        if(result == 1L){
            // 创建订单,订单项等信息
            OrderCreateTo order = this.createOrder();
        // 2.验价
            BigDecimal payAmount = order.getOrder().getPayAmount();
            BigDecimal payPrice = submitVo.getPayPrice();
            // 页面提价来的价格和实际的价格价格差值不超过 0.01 验价成功
//            if (Math.abs(payAmount.subtract(payPrice).doubleValue()) < 0.01) {
//        // 3、保存订单
            this.saveOrder(order);
            response.setOrder(order.getOrder());
//            return response;
//        // 4、库存锁定。只要有异常回滚订单数据。
                WareSkuLockVo lockVo = new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
                lockVo.setLocks(locks);
                //库存服务本身也可以使用自动解锁模式  消息
                R r = wmsFeignService.orderLockStock(lockVo);
                if (r.getCode() == 0) {
                    // 锁成功了
                    response.setOrder(order.getOrder());

        // 5、远程扣减积分 出异常
                    // 订单创建成功发送消息给MQ,订单创建成功发送一个消息给MQ,使用的是order.create.order的路由健,这个消息会在队列中存在30-40后在以另外一个路由健发送到另外一个队列中,进行消费
                    rabbitTemplate.convertAndSend("order-event-exchange", "order.create.order", order.getOrder());

        // 6、清除购物车已经下单的商品
                    cartFeignService.deleteItems();
                    return response;
                } else {
                    //锁定失败
                    String msg = (String) r.get("msg");
                    throw new NoStockException(msg);
                }
            }else {
                // 验价失败
                response.setCode(2);
                return response;
            }

        }



    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    /*
     * @param entity
     * @==============History===============<br/>
     * @Description //   实现关单
     * @Date 2023/6/18 2023/6/18 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    @Override
    public void closeOrder(OrderEntity entity) {
        // 查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        // 过了30分钟以后这个订单的订单的状态还是待付款的话,就要把这个订单给关闭了
        if (orderEntity.getStatus() == OrderStatusEnum.CREATE_NEW.getCode()) {
            // 关单
            OrderEntity update = new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo = new OrderTo();
            BeanUtils.copyProperties(orderEntity, orderTo);
            // 发给MQ一个消息
            try {
                //TODO 保证消息一定会发送出去，每一个消息都可以做好日志记录（给数据库保存每一个消息的详细信息）。
                //TODO 定期扫描数据库将失败的消息再发送一遍;          这个消息是直接绑定这库存服务,库存服务收到这个消息就马上消费这一条将这个订单的库存进行解锁
                rabbitTemplate.convertAndSend("order-event-exchange", "order.release.other", orderTo);
            } catch (Exception e) {
                //TODO 将没法送成功的消息进行重试发送。
            }
        }
    }

    /*
     * @param secKillOrder
     * @==============History===============<br/>
     * @Description //   秒杀创建订单
     * @Date 2023/6/23 2023/6/23 
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    @Override
    public void createSecKillOrder(SecKillOrderTo secKillOrder) {
        //TODO 保存订单信息
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setOrderSn(secKillOrder.getOrderSn());
        orderEntity.setMemberId(secKillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());

        BigDecimal multiply = secKillOrder.getSecKillPrice().multiply(new BigDecimal("" + secKillOrder.getNum()));
        orderEntity.setPayAmount(multiply);
        this.save(orderEntity);

        //TODO 保存订单项信息
        OrderItemEntity orderItemEntity = new OrderItemEntity();
        orderItemEntity.setOrderSn(secKillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        //TODO 获取当前SKU的详细信息进行设置  productFeignService.getSpuInfoBySkuId()
        orderItemEntity.setSkuQuantity(secKillOrder.getNum());

        orderItemService.save(orderItemEntity);
    }

    /*
     * @param orderSn
     * @param total
     * @==============History===============<br/>
     * @Description //   支付功能的实现，获取当前订单的支付信息
     * @Date 2023/5/18 2023/5/18
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return PayVo
     */
    @Override
    public PayVo getOrderPay(String orderSn) {
        PayVo payVo = new PayVo();
        OrderEntity order = this.getOrderByOrderSn(orderSn);
        // 将支付价格设置为两位小数
        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);

        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());
        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity entity = order_sn.get(0);
        payVo.setSubject(entity.getSkuName());
        payVo.setBody(entity.getSkuAttrsVals());
//        payVo.setSubject(entity.getSpuId().toString());
//        payVo.setBody(entity.getCategoryId().toString());
        return payVo;
    }

    /*
     * @param params
     * @==============History===============<br/>
     * @Description //   分页查询当前登录用户的所有订单
     * @Date 2023/5/22 2023/5/22
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return PageUtils
     */
    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>().eq("member_id", memberRespVo.getId()).orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());

        page.setRecords(order_sn);

        return new PageUtils(page);
    }

    @Override
    public R listWithItem(Map<String, Object> page) {
        return null;
    }

    /*
     * @param order
     * @==============History===============<br/>
     * @Description //   保存订单信息
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    protected void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity = order.getOrder();
        orderEntity.setCreateTime(new Date());
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);
        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }

    /*
     * @param
     * @==============History===============<br/>
     * @Description //   创建订单,订单项等信息
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return OrderCreateTo
     */
    protected OrderCreateTo createOrder() {
        OrderCreateTo createTo = new OrderCreateTo();
        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        // 1.生成订单
        OrderEntity orderEntity = this.buildOrder(orderSn);

        // 2、生成订单项
        List<OrderItemEntity> itemEntities = this.buildOrderItems(orderSn);

        // 3、计算价格、积分等相关
        this.computePrice(orderEntity, itemEntities);

        createTo.setOrder(orderEntity);

        createTo.setOrderItems(itemEntities);

        return createTo;
    }




    /*
     * @param orderSn  订单号
     * @==============History===============<br/>
     * @Description //   生成订单信息
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return OrderEntity
     */
    protected OrderEntity buildOrder(String orderSn) {
        // 获取用户的登录信息
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        OrderEntity entity = new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());
        entity.setMemberUsername(respVo.getNickname());
        // 设置运费信息
         String substring = respVo.getMobile().substring(respVo.getMobile().length() - 1, respVo.getMobile().length());

        entity.setFreightAmount(new BigDecimal(substring));
        // 设置订单的相关状态信息
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        // 设置自动确认时间为7天
        entity.setAutoConfirmDay(7);
        // 获取收货地址信息
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        if(fare.getCode() == 0){
            FareVo fareResp = fare.getData(new TypeReference<FareVo>() {});
            // 设置运费信息
            entity.setFreightAmount(fareResp.getFare());
            // 设置收货人信息
            entity.setReceiverCity(fareResp.getAddress().getCity());
            entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
            entity.setReceiverName(fareResp.getAddress().getName());
            entity.setReceiverPhone(fareResp.getAddress().getPhone());
            entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
            entity.setReceiverProvince(fareResp.getAddress().getProvince());
            entity.setReceiverRegion(fareResp.getAddress().getRegion());
        }
        return entity;
    }



    /*
     * @param orderSn  订单号
     * @==============History===============<br/>
     * @Description //   生成订单项
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return java.util.List<OrderItemEntity>
     */
    protected List<OrderItemEntity> buildOrderItems(String orderSn) {
        // 最后确定每个购物项的价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if (currentUserCartItems != null && currentUserCartItems.size() > 0) {
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
                OrderItemEntity itemEntity = this.buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);
                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;
    }

    /*
     * @param cartItem
     * @==============History===============<br/>
     * @Description //   生成订单项
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return OrderItemEntity
     */
    protected OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity = new OrderItemEntity();
        // 1、订单信息：订单号 v
        // 2、商品的SPU信息  V
        Long skuId = cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        if(r.getCode() == 0){
            SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {});

            itemEntity.setSpuId(data.getId());
            itemEntity.setSpuBrand(data.getBrandId().toString());
            itemEntity.setSpuName(data.getSpuName());
            itemEntity.setCategoryId(data.getCatalogId());
        }
        // 3、商品的sku信息  v
        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
        // 将一个list以 ";" 转换为 String
        String skuAttr = StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(), ";");
        itemEntity.setSkuAttrsVals(skuAttr);
        itemEntity.setSkuQuantity(cartItem.getCount());
        // 4、优惠信息[不做]  TODO 将来整合优惠服务
        // 5、积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        // 6、订单项的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));
        // 当前订单项的实际金额。 总额-各种优惠
        BigDecimal origin = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract = origin.subtract(itemEntity.getCouponAmount())
                .subtract(itemEntity.getPromotionAmount())
                .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);
        return itemEntity;
    }


    /*
     * @param orderEntity
     * @param itemEntities
     * @==============History===============<br/>
     * @Description //   计算价格、积分等相关
     * @Date 2023/5/13 2023/5/13
     * @Author < a href="2277411582@qq.com">chen</ a>
     * @return void
     */
    protected void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total = new BigDecimal("0.0");
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal integration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");
        BigDecimal gift = new BigDecimal("0.0");
        BigDecimal growth = new BigDecimal("0.0");
        // 订单的总额，叠加每一个订单项的总额信息
        for (OrderItemEntity entity : itemEntities) {
            coupon = coupon.add(entity.getCouponAmount());
            integration = integration.add(entity.getIntegrationAmount());
            promotion = promotion.add(entity.getPromotionAmount());
            total = total.add(entity.getRealAmount());
            gift = gift.add(new BigDecimal(entity.getGiftIntegration().toString()));
            growth = growth.add(new BigDecimal(entity.getGiftGrowth().toString()));
        }
        // 1、订单价格相关
        orderEntity.setTotalAmount(total);
        // 应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

        // 2、设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
        orderEntity.setDeleteStatus(0);//未删除
    }


}